package com.jason.library.widget.floatedit

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Handler
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.Gravity
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.*
import com.jason.library.common.R
import com.jason.library.common.utils.ScreenUtils

class CbyFloatInputWindow : PopupWindow {

    private lateinit var contentView : RelativeLayout
    private lateinit var sendBtn: Button
    private lateinit var inputEdit: EditText

    private lateinit var targetEdit: EditText

    private lateinit var context : Context

    constructor(context: Context) : super(context) {
        init(context)
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context)
    }


    private fun init(context: Context) {
        this.context = context
        createContentView(context)
        //val view = LayoutInflater.from(context).inflate(R.layout.widget_float_input, null)
        setContentView(contentView)
        width = MATCH_PARENT
        height = WRAP_CONTENT
        isFocusable = true
        // 设置SelectPicPopupWindow弹出窗体动画效果
        // animationStyle = R.style.showPopAnimation
        // 实例化一个ColorDrawable颜色为半透明
        val colorDrawable = ColorDrawable(-0x50000000)
        setBackgroundDrawable(colorDrawable)

        //inputEdit = view.findViewById(R.id.inputEdit)
        //sendBtn = view.findViewById(R.id.sendBtn)

        initView(context)
    }

    private fun createContentView(context: Context) {
        //根视图
        contentView = RelativeLayout(context).apply {
            layoutParams = RelativeLayout.LayoutParams(
                MATCH_PARENT,
                WRAP_CONTENT
            )
        }

        //中间层视图
        val inputLayuot = LinearLayout(context).apply {
            layoutParams = RelativeLayout.LayoutParams(
                MATCH_PARENT,
                ScreenUtils.dip2px(context, 46f)
            )
            //垂直方向居中
            gravity = Gravity.CENTER_VERTICAL
            //设置背景
            setBackgroundColor(Color.parseColor("#f3f4f6"))
            //水平排版
            orientation = LinearLayout.HORIZONTAL
            //设置内间距
            val padding = ScreenUtils.dip2px(context, 8f)
            setPadding(padding, 0, padding, 0)
        }


        //输入框
        inputEdit = EditText(context).apply {
            //设置输入框背景
            setBackgroundResource(R.drawable.float_input_bg_edit)
            //内容垂直方向居中
            gravity = Gravity.CENTER_VERTICAL
            //高度32dp，宽带自适应剩余空间
            layoutParams = LinearLayout.LayoutParams(0, ScreenUtils.dip2px(context, 32f), 1f).apply {
                //控件垂直方向居中
                gravity = Gravity.CENTER_VERTICAL
                //右间距8dp
                rightMargin =  ScreenUtils.dip2px(context, 8f)
            }
            setPadding(0,0,0,0)

        }

        //添加输入框
        inputLayuot.addView(inputEdit)

        //发送按钮
        sendBtn = Button(context).apply {
            //默认背景
            setBackgroundResource(R.drawable.float_input_bg_disable_button)
            //固定文按
            text = "发送"
            //文字居中限时
            gravity = Gravity.CENTER
            //字体颜色
            setTextColor(Color.parseColor("#FFFFFF"))
            //布局参数：宽度 60dp  高度 32dp
            layoutParams = LinearLayout.LayoutParams(
                ScreenUtils.dip2px(context, 60f),
                ScreenUtils.dip2px(context, 32f)
            ).apply {
                //按钮控件垂直居中
                gravity = Gravity.CENTER_VERTICAL
            }
            setPadding(0,0,0,0)
        }

        //添加按钮
        inputLayuot.addView(sendBtn)


        //添加布局到容器中
        contentView.addView(inputLayuot)
    }

    private fun initView(context: Context) {
        inputEdit.apply {
            inputType = EditorInfo.TYPE_CLASS_TEXT
            imeOptions = EditorInfo.IME_FLAG_NO_EXTRACT_UI
            addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (TextUtils.isEmpty(inputEdit.text)) {
                        sendBtn.isEnabled = false
                        sendBtn.setBackgroundResource(R.drawable.float_input_bg_disable_button)
                    } else {
                        sendBtn.isEnabled = true
                        sendBtn.setBackgroundResource(R.drawable.float_input_bg_enable_button)
                    }
                }

                override fun beforeTextChanged(
                    s: CharSequence?,
                    start: Int,
                    count: Int,
                    after: Int
                ) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

                }

            })

            setOnEditorActionListener(object : TextView.OnEditorActionListener{
                override fun onEditorAction(
                    v: TextView?,
                    actionId: Int,
                    event: KeyEvent?
                ): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEND
                        || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER
                    ) {
                        targetEdit.text = inputEdit.text
                        dismiss()
                        return true
                    }
                    return false
                }

            })
        }

        sendBtn.setOnClickListener {
            if (!TextUtils.isEmpty(inputEdit.text.toString().trim { it <= ' ' })) {
                // /提交内容
                targetEdit.text = inputEdit.text
                dismiss()
            }
        }
    }

    fun setTargetEdit(editText: EditText) {
        this.targetEdit = editText
        inputEdit.text = targetEdit.text
        inputEdit.setSelection(targetEdit.length())
        inputEdit.inputType = targetEdit.inputType
        inputEdit.keyListener = targetEdit.keyListener
    }


    fun show(anchorView: View?) {
        openKeyboard()
        showAtLocation(
            anchorView, Gravity.BOTTOM
                    or Gravity.CENTER_HORIZONTAL, 0, 0
        )
    }

    private fun openKeyboard() {
        val handler = Handler()
        if (inputEdit != null) {
            inputEdit.isFocusable = true
            inputEdit.requestFocus()
        }
        handler?.postDelayed({
            try {
                val imm = context
                    .getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.showSoftInput(inputEdit, 0)
            } catch (e: Exception) {
            }
        }, 200)
    }
}